import { isExt } from "~/helpers/vars"

/**
 * 将 web 的 localStorage 与 chrome.storage.sync 封装在一起，
 * 以便代码可以同时运行在 web 和 chrome 插件中
 */
export default {
  async set(items: Record<string, any>) {
    if (isExt) {
      await chrome.storage.sync.set(items)
    } else {
      Object.entries(items).forEach(([key, val]) => {
        localStorage.setItem(key, JSON.stringify(val))
      })
    }
  },
  async get(keys?: string | string[]) {
    keys = Array.isArray(keys) ? keys : (typeof keys === 'string' ? [keys] : undefined)
    if (isExt) {
      return await chrome.storage.sync.get(keys)
    }

    keys = keys || Object.keys(localStorage)
    return keys.reduce((prev, k) => {
      const v = localStorage.getItem(k)
      prev[k] = v ? JSON.parse(v) : null
      return prev
    }, {} as Record<string, any>)
  },
  async remove(keys: string | string[]) {
    if (isExt) {
      await chrome.storage.sync.remove(keys)
    } else {
      keys = Array.isArray(keys) ? keys : [keys]
      keys.forEach(k => k && localStorage.removeItem(k))
    }
  },
  async clear() {
    isExt ? await chrome.storage.sync.clear() : localStorage.clear()
  }
}
